package commons;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;

import commons.Player;
import commons.Status;

/**
 * 
 * World object. The state of the entire game space. 
 * GAME SPECIFIC, in our case a simple grid based game.
 *
 */
public class World extends Status implements Serializable {
	private static final long serialVersionUID = 1L;
	private HashMap<Integer, Player> players;
	private String name; 
	public static final int MAX_X = 20;
	public static final int MAX_Y = 10;
	
	// Only constructor
	public World(String name) {
		this.name = name;
		players = new HashMap<Integer, Player>();
	}
	
	public String getName() {
		return this.name;
	}
	
	// Updates a player
	public synchronized void updatePlayer(Integer key, Player updatedPlayer) {
		players.put(key, updatedPlayer);
		changed();
	}
	
	// Removes a player from the wold
	public synchronized void removePlayer(Integer key) {
		players.remove(key);
		changed();
	}

	
	///
	/// Displays the World by first showing the player names
	/// the showing their placement on the grid
	///
	public void display() {
		System.out.println();
		System.out.println(name);
		for(int x = 0; x < name.length(); x++)
			System.out.print("=");
		System.out.println();
		
		Integer[][] board = new Integer[MAX_Y][MAX_X];
		for(Iterator<Integer> keys = players.keySet().iterator(); keys.hasNext();) {
			Integer key = keys.next();
			Player player = players.get(key);
			board[player.getY()][player.getX()] = key;
			System.out.println("Player [" + key +"] is at  (" + player.getY() + ", " + player.getX()+") ~ " + player.getName());
		}
		
		System.out.print("+");
		for(int x = 0; x < MAX_X; x++) 
			System.out.print("-");
		System.out.println("+");
		
		for(int y = 0; y < MAX_Y; y++) {
			System.out.print("|");
			for(int x = 0; x < MAX_X; x++) {
				if(board[y][x] == null) {
					System.out.print(" ");
				} else {					
					System.out.print(board[y][x]);
				}
			}
			System.out.println("|");
		}
		System.out.print("+");
		for(int x = 0; x < MAX_X; x++) 
			System.out.print("-");
		System.out.println("+");
	}
}
